#include "userdelete.h"
#include "ui_userdelete.h"
#include "msgbox.h"
#include "userlogger.h"

UserDelete::UserDelete(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserDelete)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::sendDeleteUserSignal, this, &UserDelete::setUser);
    connect(bdf, &BllDataFlow::sendDeleteUserSignal, this, &UserDelete::updateLableQuestion);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &UserDelete::retranslateUiSlot);

    initWidget();
}

UserDelete::~UserDelete()
{
    delete ui;
}

void UserDelete::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

void UserDelete::on_btnClose_clicked()
{
    this->hide();
}

void UserDelete::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void UserDelete::on_btnCancel_clicked()
{
    this->hide();
}

void UserDelete::on_btnOK_clicked()
{
    EttaError ret = sqlHelper->deleteUser(user);
    if (ret == EttaError::OK)
    {
        QString message = QString("%1: %2").arg(tr("Delete User")).arg(user.name);
        UserLogger::log(message);
        bdf->showAllUsers();
        this->hide();
    }
    else
    {
        UserLogger::error(QString(tr("Failed to Delete User %1")).arg(user.name));
        QString result = (ret == EttaError::OK) ? tr("Success") : tr("Failed");
        MsgBox::information(this, tr("Delete User"), QString(tr("%1 to Delete User")).arg(result));
    }
}

void UserDelete::setUser(User user_)
{
    user = user_;
    bool state = sqlHelper->checkUserIsOn(user.name);
    if (state)
    {
        MsgBox::information(this,QString(tr("User")),QString(tr("User status is on!")));
        this->hide();
    }
    else
    {
        this->show();
    }

}

void UserDelete::updateLableQuestion()
{
    ui->lblUserDelQuestion->setText(QString(tr("Would you like to delete %1 ?")).arg(user.name));
}

void UserDelete::initWidget()
{
    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0,0,0,150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget_2->setGraphicsEffect(shadow);
}
